﻿using AutoMapper;
using Domain.Production_Modules;
using Infratructure.Interface;
using MediatR;
using MES.Server.API.Application.Command.Production_Modules;
using ReturnValue;
using Yitter.IdGenerator;

namespace MES.Server.API.Application.Handler.Production_Modules
{
   
    /// <summary>
    /// 物料库存添加命令处理
    /// </summary>
    public class WarehouseCreateCommandHandler : IRequestHandler<WarehouseCreateCommand, ApiResult<int>>
    {
        /// <summary>
        /// 物料库存
        /// </summary>
        IRepository<WarehouseModel> _inventoryRepository;
        /// <summary>
        /// Mappering
        /// </summary>
        IMapper _mapper;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="inventoryRepository">物料库存</param>
        /// <param name="mapper">Mappering</param>
        public WarehouseCreateCommandHandler(IRepository<WarehouseModel> inventoryRepository, IMapper mapper)
        {
            _inventoryRepository = inventoryRepository;
            _mapper = mapper;
        }
        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> Handle(WarehouseCreateCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            WarehouseModel model = _mapper.Map<WarehouseModel>(request);
            model.CreateTime = DateTime.Now;
             model.Id = YitIdHelper.NextId();
            var r = await _inventoryRepository.AddAsync(model);
            if (r > 0)
            {
                result = new ApiResult<int>().AddSuccess("物料仓库", r);
            }
            else
            {
                result = new ApiResult<int>().AddFail("物料仓库");
            }

            return await Task.FromResult(result);
        }
    }
}
